package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.mapper.SysMenuMapper;
import com.caifu.mapper.SysRoleMenuMapper;
import com.caifu.mapper.SysUserMapper;
import com.caifu.pojo.*;
import com.caifu.mapper.SysRoleMapper;
import com.caifu.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caifu.util.CopyBen;
import com.caifu.util.OrgTypeSort;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author szt
 * @since 2020-11-17
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysRoleMenuMapper roleMenuMapper;
    @Resource
    private SysMenuMapper menuMapper;
    @Resource
    private SysUserMapper userMapper;

    @Override
    @Transactional
    public Result save(int userNo, String roleNo, String roleName, String roleDesc, String menuArr) throws Exception {
        SysUser user = new SysUser();
        SysRole role = new SysRole();
        try {

            user = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no",userNo));
            if(user==null){
                throw new Exception("在SysUser表中找不到用户信息");
            }

            if(StringUtils.isBlank(roleNo)){
                //添加角色
                role = new SysRole();
                role.setName(roleName);
                role.setRoleDesc(roleDesc);
                role.setSort(999);
                role.setPreinstall("0");
                role.setState("1");
                role.setCreatedTime(new Date());
                roleMapper.insert(role);

                //更新授权
                String arr[] = arrDisitinct(menuArr);
                for (String str:arr) {
                    SysRoleMenu menu = new SysRoleMenu();
                    SysMenu sysMenu = menuMapper.selectById(Integer.parseInt(str));
                    SysMenu sysMoudelMenu = menuMapper.selectById(sysMenu.getParentNo());
                    SysMenu appMenu = menuMapper.selectById(sysMoudelMenu.getParentNo());
                    menu.setRoleId(role.getId());
                    menu.setMenuId(Integer.parseInt(str));
                    menu.setCreatedTime(new Date());
                    menu.setAppMenuId(appMenu.getParentNo());
                    roleMenuMapper.insert(menu);
                }

                //日志记录  sys 组织架构模块  sys-300 角色添加 sys-301 角色修改
                SysLog log = new SysLog(userNo, user.getPostType(),"sys", "sys-300", "1", user.getLoginName()+"新增角色成功[roleNo="+role.getId()+", roleName="+role.getName()+"]！", new Date());
                return ResultUtil.retLog(200,"添加成功！",log);
            }else{
                role = roleMapper.selectOne(new QueryWrapper<SysRole>().eq("id",roleNo));
                role.setName(roleName);
                role.setRoleDesc(roleDesc);
                role.setUpdatedTime(new Date());
                roleMapper.updateById(role);

                //更新授权
                roleMenuMapper.delete(new QueryWrapper<SysRoleMenu>().eq("role_id",roleNo));
                String arr[] = arrDisitinct(menuArr);
                for (String str:arr) {
                    SysRoleMenu menu = new SysRoleMenu();
                    SysMenu sysMenu = menuMapper.selectById(Integer.parseInt(str));
                    SysMenu sysMoudelMenu = menuMapper.selectById(sysMenu.getParentNo());
                    SysMenu appMenu = menuMapper.selectById(sysMoudelMenu.getParentNo());
                    menu.setRoleId(role.getId());
                    menu.setMenuId(Integer.parseInt(str));
                    menu.setCreatedTime(new Date());
                    menu.setAppMenuId(appMenu.getParentNo());
                    roleMenuMapper.insert(menu);
                }

                //日志记录  sys 组织架构模块  sys-300 角色添加 sys-301 角色修改
                SysLog log = new SysLog(userNo, user.getPostType(),"sys", "sys-301", "1", user.getLoginName()+"修改角色成功[roleNo="+role.getId()+", roleName="+role.getName()+"]！", new Date());
                return ResultUtil.retLog(200,"修改成功！",log);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //日志记录  sys 组织架构模块  sys-300 角色添加 sys-301 角色修改
            if(StringUtils.isBlank(roleNo)){
                SysLog log = new SysLog(userNo, user.getPostType(),"sys", "sys-300", "9", user.getLoginName()+"添加角色失败[roleNo="+role.getId()+", roleName="+role.getName()+"]！", new Date());
                return ResultUtil.retLog(199,"添加失败！",log);
            }else{
                SysLog log = new SysLog(userNo, user.getPostType(),"sys", "sys-301", "9", user.getLoginName()+"修改角色失败[roleNo="+role.getId()+", roleName="+role.getName()+"]！", new Date());
                return ResultUtil.retLog(199,"修改失败！",log);
            }

        }

    }

    //去重
    private static String[] arrDisitinct(String arr){
        if(arr.length()>0){
            arr=arr.substring(0,arr.length()-1);
            String[] test1 = arr.split("\\|");
            ArrayList list = new ArrayList();
            for (int i = 0; i < test1.length; i++) {
                if (!list.contains(test1[i]))
                    list.add(test1[i]);
            }
            String str = list.toString().replaceAll("\\[","").replaceAll("\\]","")+",";
            return str.replaceAll(" ","").split(",");
        }else{
            return null;
        }

    }

}

